/**
 * 表格数据管理组合函数
 */
import { ref, readonly } from 'vue'
import type { TableDataItem, ApiResponse } from '../types/app'

export function useTableData() {
  // 表格数据状态
  const tableData = ref<TableDataItem[]>([])
  const loading = ref<boolean>(false)
  const error = ref<string | null>(null)

  // 模拟数据生成器
  const mockDataMap: Record<string, TableDataItem[]> = {
    // 基础组件数据
    'button': [
      { 
        id: 1, 
        name: '主要按钮', 
        category: '按钮', 
        description: '用于主要操作的按钮组件，具有较高的视觉权重', 
        createTime: '2024-01-01 10:00:00', 
        status: 'active', 
        statusText: '启用',
        props: { type: 'primary', size: 'medium' }
      },
      { 
        id: 2, 
        name: '次要按钮', 
        category: '按钮', 
        description: '用于次要操作的按钮组件', 
        createTime: '2024-01-02 11:30:00', 
        status: 'active', 
        statusText: '启用',
        props: { type: 'secondary', size: 'medium' }
      },
      { 
        id: 3, 
        name: '危险按钮', 
        category: '按钮', 
        description: '用于危险操作的按钮组件，如删除等', 
        createTime: '2024-01-03 14:20:00', 
        status: 'inactive', 
        statusText: '禁用',
        props: { type: 'danger', size: 'medium' }
      }
    ],

    // 输入框组件数据
    'input': [
      { 
        id: 4, 
        name: '文本输入框', 
        category: '输入框', 
        description: '基础的文本输入组件', 
        createTime: '2024-01-04 09:15:00', 
        status: 'active', 
        statusText: '启用',
        props: { placeholder: '请输入内容', maxLength: 100 }
      },
      { 
        id: 5, 
        name: '数字输入框', 
        category: '输入框', 
        description: '专门用于数字输入的组件', 
        createTime: '2024-01-05 16:45:00', 
        status: 'active', 
        statusText: '启用',
        props: { min: 0, max: 999999, step: 1 }
      },
      {
        id: 6,
        name: '密码输入框',
        category: '输入框',
        description: '用于密码输入的安全组件',
        createTime: '2024-01-06 13:22:00',
        status: 'active',
        statusText: '启用',
        props: { type: 'password', showPassword: true }
      }
    ],

    // 表格组件数据
    'table': [
      { 
        id: 7, 
        name: '基础表格', 
        category: '表格', 
        description: '用于展示结构化数据的表格组件', 
        createTime: '2024-01-07 08:30:00', 
        status: 'active', 
        statusText: '启用',
        features: ['排序', '筛选', '分页']
      },
      { 
        id: 8, 
        name: '可编辑表格', 
        category: '表格', 
        description: '支持行内编辑的表格组件', 
        createTime: '2024-01-08 12:10:00', 
        status: 'active', 
        statusText: '启用',
        features: ['行内编辑', '数据校验', '批量操作']
      },
      {
        id: 9,
        name: '树形表格',
        category: '表格',
        description: '支持树形结构数据展示的表格',
        createTime: '2024-01-09 15:18:00',
        status: 'pending',
        statusText: '开发中',
        features: ['树形展示', '层级操作', '懒加载']
      }
    ],

    // 选择器组件数据
    'select': [
      { 
        id: 10, 
        name: '基础选择器', 
        category: '选择器', 
        description: '单选下拉选择组件', 
        createTime: '2024-01-10 10:25:00', 
        status: 'active', 
        statusText: '启用',
        options: { multiple: false, clearable: true }
      },
      { 
        id: 11, 
        name: '多选选择器', 
        category: '选择器', 
        description: '支持多选的下拉选择组件', 
        createTime: '2024-01-11 14:40:00', 
        status: 'active', 
        statusText: '启用',
        options: { multiple: true, maxTagCount: 3 }
      }
    ],

    // 级联选择器数据
    'cascader': [
      {
        id: 12,
        name: '基础级联选择器',
        category: '级联选择器',
        description: '支持层级选择的级联选择组件',
        createTime: '2024-01-12 11:15:00',
        status: 'active',
        statusText: '启用',
        features: ['多级选择', '任意层级选择', '搜索功能']
      }
    ],

    // 默认数据
    'default': [
      {
        id: 999,
        name: '示例数据',
        category: '通用',
        description: '这是一个示例数据项',
        createTime: '2024-01-01 00:00:00',
        status: 'active',
        statusText: '启用'
      }
    ]
  }

  /**
   * 模拟API请求延迟
   */
  const delay = (ms: number): Promise<void> => {
    return new Promise(resolve => setTimeout(resolve, ms))
  }

  /**
   * 获取表格数据
   */
  const fetchTableData = async (category: string): Promise<TableDataItem[]> => {
    loading.value = true
    error.value = null

    try {
      // 模拟网络请求延迟
      await delay(800 + Math.random() * 1200)

      // 模拟偶尔的网络错误（5%概率）
      if (Math.random() < 0.05) {
        throw new Error('网络请求失败，请稍后重试')
      }

      // 获取对应分类的数据
      const data = mockDataMap[category] || mockDataMap['default']
      
      // 模拟数据处理
      const processedData = data.map(item => ({
        ...item,
        // 添加一些动态计算的字段
        updateTime: new Date().toLocaleString(),
        version: `v${Math.floor(Math.random() * 5) + 1}.${Math.floor(Math.random() * 10)}.${Math.floor(Math.random() * 10)}`
      }))

      tableData.value = processedData
      return processedData

    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '未知错误'
      error.value = errorMessage
      tableData.value = []
      throw err
    } finally {
      loading.value = false
    }
  }

  /**
   * 刷新表格数据
   */
  const refreshTableData = async (category: string): Promise<void> => {
    await fetchTableData(category)
  }

  /**
   * 清空表格数据
   */
  const clearTableData = (): void => {
    tableData.value = []
    error.value = null
  }

  /**
   * 模拟数据更新（用于演示实时更新）
   */
  const updateTableItem = (id: number, updates: Partial<TableDataItem>): boolean => {
    const index = tableData.value.findIndex(item => item.id === id)
    if (index !== -1) {
      tableData.value[index] = { ...tableData.value[index], ...updates }
      return true
    }
    return false
  }

  /**
   * 删除表格项
   */
  const deleteTableItem = (id: number): boolean => {
    const index = tableData.value.findIndex(item => item.id === id)
    if (index !== -1) {
      tableData.value.splice(index, 1)
      return true
    }
    return false
  }

  /**
   * 批量操作
   */
  const batchUpdateStatus = (ids: number[], status: TableDataItem['status']): void => {
    tableData.value.forEach(item => {
      if (ids.includes(item.id)) {
        item.status = status
        item.statusText = status === 'active' ? '启用' : status === 'inactive' ? '禁用' : '开发中'
      }
    })
  }

  /**
   * 搜索表格数据
   */
  const searchTableData = (keyword: string): TableDataItem[] => {
    if (!keyword.trim()) {
      return tableData.value
    }

    const lowerKeyword = keyword.toLowerCase()
    return tableData.value.filter(item => 
      item.name.toLowerCase().includes(lowerKeyword) ||
      item.category.toLowerCase().includes(lowerKeyword) ||
      item.description.toLowerCase().includes(lowerKeyword)
    )
  }

  /**
   * 排序表格数据
   */
  const sortTableData = (key: keyof TableDataItem, order: 'asc' | 'desc' = 'asc'): void => {
    tableData.value.sort((a, b) => {
      const aValue = a[key]
      const bValue = b[key]
      
      if (typeof aValue === 'string' && typeof bValue === 'string') {
        return order === 'asc' 
          ? aValue.localeCompare(bValue)
          : bValue.localeCompare(aValue)
      }
      
      if (typeof aValue === 'number' && typeof bValue === 'number') {
        return order === 'asc' ? aValue - bValue : bValue - aValue
      }
      
      return 0
    })
  }

  return {
    // 响应式状态
    tableData: readonly(tableData),
    loading: readonly(loading),
    error: readonly(error),

    // 数据操作方法
    fetchTableData,
    refreshTableData,
    clearTableData,
    updateTableItem,
    deleteTableItem,
    batchUpdateStatus,
    searchTableData,
    sortTableData
  }
}
